import { defineStore } from 'pinia'
import{ref} from 'vue'
import { loginAPI } from '@/apis/user.js'
import { useCartStore } from './cartStore'
import { mergeCartAPI } from '@/apis/cart'
export const useUserStore = defineStore('user',()=> {
  const cartStore = useCartStore()
  // 定义用户数据state
  const userInfo = ref({})
  // 定义获取用户数据接口
  const getUserInfo = async ({ account, password })=>{
  const res = await loginAPI({ account, password })
  userInfo.value = res.result
// 合并购物车
    await mergeCartAPI(cartStore.cartList.map((item) =>{
      return {
        skuId:item.skuId,
        selected:item.selected,
        count:item.count
      }
    }) )
    cartStore.updateNewList()

}
  // 退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
  }
  // 以对象格式把state action return出去
  return{
    userInfo,
    getUserInfo,
    clearUserInfo,
    
  }
 
},

  {
    persist: true
  }

)